/*
 * Copyright (C) 2008 Matt Falkoski
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.falko.android.raven.settings;

import android.content.Context;
import android.content.res.TypedArray;
import android.preference.Preference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ViewSwitcher;

import com.falko.android.raven.R;
import com.falko.android.raven.util.AndroidUtil;

public class ImageSwitcherPreference extends Preference implements
		AdapterView.OnItemSelectedListener {

	private static final int DEFAULT_VALUE = 5;
	private final String TAG = getClass().getName();
	private ImageSwitcher imageSwitcher_ = null;
	private Gallery gallery_ = null;
	private int textureID_ = 0;
	private int[] imageIds_ = null;

	public ImageSwitcherPreference(Context context) {
		super(context);
		initPreference(context, null);
	}

	public ImageSwitcherPreference(Context context, AttributeSet attrs) {
		super(context, attrs);
		initPreference(context, attrs);
	}

	public ImageSwitcherPreference(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);
		initPreference(context, attrs);
	}

	private void initPreference(Context context, AttributeSet attrs) {
		imageIds_ = AndroidUtil.getAllResourceIDs(R.drawable.class);
	}

	@Override
	protected View onCreateView(ViewGroup parent) {

		RelativeLayout layout = null;
		try {
			LayoutInflater inflater = (LayoutInflater) getContext()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			layout = (RelativeLayout) inflater.inflate(
					R.layout.image_switcher_preference, parent, false);
		} catch (Exception e) {
			Log.e(TAG, "Error creating seek bar preference", e);
		}

		gallery_ = (Gallery) layout.findViewById(R.id.gallery);
		gallery_.setAdapter(new ImageAdapter(getContext()));
		gallery_.setOnItemSelectedListener(this);

		imageSwitcher_ = (ImageSwitcher) layout
				.findViewById(R.id.imageSwitcher);
		imageSwitcher_.setFactory(new ViewFactory());
		return layout;
	}

	@Override
	public void onBindView(View view) {

		super.onBindView(view);
		gallery_.setSelection(textureID_);
		imageSwitcher_.setImageResource(imageIds_[textureID_]);
	}

	@Override
	protected Object onGetDefaultValue(TypedArray ta, int index) {

		int defaultValue = ta.getInt(index, DEFAULT_VALUE);
		return defaultValue;

	}

	@Override
	protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {

		if (restoreValue) {
			textureID_ = getPersistedInt(textureID_);
		} else {
			try {
				textureID_ = (Integer) defaultValue;
			} catch (Exception ex) {
				Log.e(TAG, "Invalid default value: " + defaultValue.toString());
			}
			persistInt(textureID_);
		}
	}

	public void onItemSelected(AdapterView<?> parent, View v, int position,
			long id) {

		if (position == textureID_ || !callChangeListener(position)) {
			return;
		}

		if (!callChangeListener(position)) {
			gallery_.setSelection(textureID_);
			return;
		}

		textureID_ = position;
		persistInt(textureID_);
		imageSwitcher_.setImageResource(imageIds_[textureID_]);
		// notifyChanged(); //for some reason this is causing an issue
		// with the smoothness of the scrolling ... go figure
	}

	public void onNothingSelected(AdapterView<?> parent) {
	}

	private class ViewFactory implements ViewSwitcher.ViewFactory {

		public ViewFactory() {
		}

		public View makeView() {
			ImageView iv = new ImageView(getContext());
			iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
			iv.setLayoutParams(new ImageSwitcher.LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
			return iv;
		}

	}

	public class ImageAdapter extends BaseAdapter {

		private Context context_;

		public ImageAdapter(Context c) {
			context_ = c;
		}

		public int getCount() {
			return imageIds_.length;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView i = new ImageView(context_);

			i.setImageResource(imageIds_[position]);
			i.setAdjustViewBounds(true);
			i.setLayoutParams(new Gallery.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			return i;
		}
	}

}
